package com.googlecode.bizyap.core.logging;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public abstract class LoggerFactory {
	
	final ConcurrentMap<String, Logger> loggers = new ConcurrentHashMap<String, Logger>();
	
	protected abstract Logger createLogger(String name);

	final Logger _getLogger(String name) {
		Logger logger = loggers.get(name);
		if(logger == null) {
			logger = createLogger(name);
			Logger oldLogger = loggers.putIfAbsent(name, logger);
			if(oldLogger != null) {
				logger = oldLogger;
			}
		}
		return logger;
	}
	
	
	private static volatile LoggerFactory factory;
	
	public static final Logger getLogger(Class clazz) {
		return getLogger(clazz.getName());
	}
	
	public static final Logger getLogger(String name) {
		return getFactory()._getLogger(name);
	}
	
	private static LoggerFactory getFactory() {
		if(factory == null) {
			synchronized (LoggerFactory.class) {
				if(factory == null) {
//					String type = AgentService.get().getLoggerType();
					String classname = "com.googlecode.bizyap.core.logging.JdkLoggerFactory";
//					if("log4j".equals(type)) {
//						classname = "com.googlecode.bizyap.core.logging.Log4jLoggerFactory";
//					}

					try {
						Class clazz = LoggerFactory.class.getClassLoader().loadClass(classname);
						factory = (LoggerFactory) clazz.newInstance();
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
				}
			}
		}
		return factory;
	}
}
